package panda.query.scan.index;

import panda.index.Index;
import panda.query.scan.Scanner;
import panda.query.scan.TableScanner;
import panda.query.struct.Attribute;
import panda.query.struct.Constant;

public class IndexJoinScanner implements Scanner {
	private Scanner l;
	private TableScanner r;
	private Index idx;
	private Attribute lattr;
	
	public IndexJoinScanner(Scanner l, Index idx, Attribute lattr, TableScanner r) {
		this.l = l;
		this.idx = idx;
		this.lattr = lattr;
		this.r = r;
		init();
	}
	
	public void init() {
		l.init();
		l.next();
		findKey();
	}
	
	public boolean next() {
		while (true) {
			if (idx.getNext()) {
				r.setCursor(idx.getTupleToken());
				return true;
			}
			if (!l.next()) return false;
			findKey();
		}
	}

	@Override
	public void close() {
		r.close();
		idx.close();
		l.close();
	}

	public Constant getValue(Attribute attr) {
		if (l.hasAttribute(attr))
			return l.getValue(attr);
		else
			return r.getValue(attr);
	}

	public boolean hasAttribute(Attribute name) {
		return l.hasAttribute(name) || r.hasAttribute(name);
	}
	
	private void findKey() {
		idx.findSpecial(l.getValue(lattr), Index.EQ);
	}

}
